<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>05.提交JSON给服务端</title>
  </head>

  <body>
    <p>姓名:<input type="text" id="name"></p>
    <p>密码:<input type="text" id="pw"></p>
    <p><button id="btn">提交</button></p>
  </body>
  <script>
    let id = document.querySelector("#name");
    let pw = document.querySelector("#pw");
    let btn = document.querySelector("#btn");
    btn.addEventListener("click", () => {
      let name = id.value;
      pw = pw.value;
      const xhr = new XMLHttpRequest();
      xhr.open('post', 'http://127.0.0.1:3000/json');
      // 设置请求参数格式的类型
      xhr.setRequestHeader('Content-Type', 'application/json');
      let json = {
        name: name,
        password: pw
      }
      console.log(JSON.stringify(json));
      // jso字符串需要转换为字符串JSON.stringify()
      xhr.send(JSON.stringify(json));
      xhr.onload = function () {
        console.log(xhr.response);
      }
    })
  </script>

</html>